package com.lu.search.service.impl;

import com.lu.model.common.dtos.ResponseResult;
import com.lu.model.common.enums.AppHttpCodeEnum;
import com.lu.model.search.dto.ApUserSearchHistoryDto;
import com.lu.model.user.pojo.ApUser;
import com.lu.search.mapper.ApUserSearchMapper;
import com.lu.search.pojo.ApUserSearch;
import com.lu.search.service.ApUserSearchService;
import com.lu.utils.thread.ApUserSearchThreadLocalUtil;
import com.mongodb.client.result.DeleteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


@Slf4j
@Service
@Transactional
public class ApUserSearchServiceImpl implements ApUserSearchService {

    @Autowired
    private MongoTemplate mongoTemplate;
    /**
     * 保存用户搜索历史纪录
     * @param keyword
     * @param userId
     */
    @Override
    @Async
    public void insert(String keyword, Integer userId) {
        //1.查询当前用户搜索的关键词
        Query query = Query.query(Criteria.where("userId").is(userId).and("keyword").is(keyword));
        ApUserSearch apUserSearch = mongoTemplate.findOne(query, ApUserSearch.class);
        //2.如果存在该关键词,就要更新创建时间
        if (apUserSearch != null) {
            apUserSearch.setCreatedTime(new Date());
            mongoTemplate.save(apUserSearch);
            return;
        }
        //3.如果关键词不存在,先判断历史记录的总关键词数量是否超过十个
        apUserSearch = new ApUserSearch();
        apUserSearch.setUserId(userId);
        apUserSearch.setKeyword(keyword);
        apUserSearch.setCreatedTime(new Date());

        Query query1 = Query.query(Criteria.where("userId").is(userId));
        query1.with(Sort.by(Sort.Direction.DESC, "createdTime"));
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(query1, ApUserSearch.class);

        if (apUserSearchList == null || apUserSearchList.size() < 10) {
            mongoTemplate.save(apUserSearch);
        } else {
            //替换
            ApUserSearch userSearch = apUserSearchList.get(apUserSearchList.size() - 1);
            mongoTemplate.findAndReplace(Query.query(Criteria.where("id").is(userSearch.getId())), apUserSearch);
        }
    }


    /**
     * 查询用户搜索历史记录
     * @return
     */
    @Override
    public ResponseResult findSearchHistory() {
        //获取当前用户
        ApUser appUser = ApUserSearchThreadLocalUtil.getAppUser();
        if (appUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //根据用户查询搜索记录，并且根据时间倒叙
        List<ApUserSearch> apUserSearchList = mongoTemplate.find(Query.query(Criteria.where("userId").is(appUser.getId())).with(Sort.by(Sort.Direction.DESC, "createdTime")), ApUserSearch.class);
        return ResponseResult.okResult(apUserSearchList);
    }

    @Override
    public ResponseResult removeSearchHistory(ApUserSearchHistoryDto dto) {
        if (dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }

        //判断是否登录
        ApUser appUser = ApUserSearchThreadLocalUtil.getAppUser();
        if (appUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //删除
        mongoTemplate.remove(Query.query(Criteria.where("userId").is(appUser.getId()).and("id").is(dto.getId())), ApUserSearch.class);

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }
}
